package de.tum.in.eist.poll.client;

import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

import de.tum.in.eist.poll.pub.shared.Lecture;
import de.tum.in.eist.poll.pub.shared.User;


/**
 * This class provides the Admin a View, where he 
 * is able to choose, which statistic has to be shown
 */
public class AdminSelectLectureView extends VerticalPanel {
	private ListBox lecturesSelect = new ListBox();
	private List<Lecture> lectures;
	private User user;
	private HorizontalPanel selectPanel = new HorizontalPanel();
	private Button logout = new Button();
	
	/**
	 * Initializes an AdminSelectLectureView-object
	 */	
	public AdminSelectLectureView(){
		this.user = EIST_POLL.currentUser;
		if(user == null){
			Window.Location.reload();
		}
		AsyncCallback<List<Lecture>> callback = new AsyncCallback<List<Lecture>>() {

			@Override
			public void onFailure(Throwable caught) {

			}

			@Override
			public void onSuccess(List<Lecture> result) {
				buildView(result);				
			}
		};
		
		EIST_POLL.service.getLectures(user, callback);
	}
	
	/**
	 * builds the admin-interface
	 * 
	 * @param lectures is a list of all lectures
	 */
	private void buildView(final List<Lecture> lectures){
		this.lectures = lectures;
		if(lectures == null)
			return;
		ListIterator<Lecture> iterator = this.lectures.listIterator();
		lecturesSelect.addItem("select the Lecture");
		while(true){
			try{
				lecturesSelect.addItem(iterator.next().getName(), ""+iterator.previousIndex());
			}
			catch(NoSuchElementException e){
				break;
			}
		}
		
		lecturesSelect.addChangeHandler(new ChangeHandler() {
			
			@Override
			public void onChange(ChangeEvent event) {
				int indx = lecturesSelect.getSelectedIndex();
				RootPanel root = RootPanel.get("main");
				root.clear();
				root.add(new AdminStatisticView(lectures.get(new Integer(lecturesSelect.getValue(indx)))));
			}
		});
		
		
		this.add(selectPanel);
		this.add(lecturesSelect);
	}
	
}

